import MaterialIcons from "@expo/vector-icons/MaterialIcons";
import { useCallback, useEffect, useRef, useState } from "react";
import {
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import TypeModal from "./typeModal";
type Props = {
  allCategoryList: Category[];
  onCategoryChange: (category: Category) => void;
};
// eslint-disable-next-line react/display-name
export default ({ allCategoryList, onCategoryChange }: Props) => {
  const modalRef = useRef<{
    show: () => void;
    hide: () => void;
  }>(null);
  const [category, setCategory] = useState<Category>();
  const [myTypeList, setMyTypeList] = useState<Category[]>([]);
  useEffect(() => {
    setMyTypeList(allCategoryList.filter((i) => i.isAdd));
    setCategory(myTypeList.find((i) => i.name === "推荐"));
  }, []);
  const onAllCategoryListChange = (categoryList: Category[]) => {
    setMyTypeList(categoryList.filter((i) => i.isAdd));
  };
  const handlePress = useCallback((item: Category) => {
    setCategory(item);
    onCategoryChange(item);
  }, []);
  return (
    <View style={styles.container}>
      <ScrollView
        horizontal
        keyboardDismissMode="on-drag"
        scrollEventThrottle={16}
      >
        {myTypeList.map((item, index) => (
          <TouchableOpacity
            key={index}
            style={styles.itemBox}
            onPress={() => handlePress(item)}
          >
            <Text
              style={[
                styles.itemText,
                category?.name === item.name && styles.activeItemText,
              ]}
            >
              {item.name}
            </Text>
          </TouchableOpacity>
        ))}
      </ScrollView>
      <TouchableOpacity onPress={() => modalRef.current?.show()}>
        <MaterialIcons name="keyboard-arrow-down" size={24} color="black" />
      </TouchableOpacity>
      <TypeModal
        ref={modalRef}
        categoryList={allCategoryList}
        onCategoryListChange={onAllCategoryListChange}
      />
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    flexDirection: "row",
    paddingHorizontal: 12,
    paddingVertical: 6,
    backgroundColor: "#fff",
  },
  scrollBox: {
    marginHorizontal: 12,
    paddingVertical: 4,
  },
  itemBox: {
    paddingRight: 26,
  },
  itemText: {
    fontSize: 16,
    color: "#999",
  },
  activeItemText: {
    fontSize: 16,
    color: "#333",
    fontWeight: "bold",
  },
});
